package com.quanyan.stadium.utils;

import com.quanyan.common.utils.CommonUtils;

import java.io.UnsupportedEncodingException;

/**
 * Created by xiaoxiao on 16/5/27.
 */
public class OrderUtils {

    private static String DEFALUT_GAME_ORDER_TOKEN = "game_order_linger_";

    private static final String BUISNESS_CODE = "001";  //暂且任务业务编码是001

    public static String generateOrderToken(String orderNo){
        String content = DEFALUT_GAME_ORDER_TOKEN + orderNo;
        if (StringUtils.isEmpty(content)) {
            return "";
        }
        try {
            content = new String(orderNo.getBytes(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new sun.misc.BASE64Encoder().encode(content.getBytes());
    }

    public static boolean validateOrderToken(String orderNo, String orderToken){
        return orderToken.equals(generateOrderToken(orderNo));
    }

    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * 转换字节数组为16进制字串
     *
     * @param b 字节数组
     * @return 16进制字串
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    public static String generateOutDoorOrderNo(Integer uid){
        return CommonUtils.generateOrderNo(uid);
    }

    /**
     * 根据户外订单号生产业务系统的订单号
     *
     * */
    public static String generateOrderNoByOutDoorOrderNo(String outDoorOrderNo){
        return BUISNESS_CODE + outDoorOrderNo;
    }


    /**
     * 根据业务系统的订单号生产户外订单号
     *
     * */
    public static String generateOutDoorOrderNoByOrderNo(String orderNo){
        return orderNo.substring(BUISNESS_CODE.length());
    }
}
